package com.woniuxy.school.user.controller;


import cn.hutool.core.bean.BeanUtil;
import com.woniuxy.commons.core.model.Result;
import com.woniuxy.commons.core.util.JwtUtil;
import com.woniuxy.school.user.dto.AccountDto;
import com.woniuxy.school.user.dto.LoginDto;
import com.woniuxy.school.user.from.LoginForm;
import com.woniuxy.school.user.service.AccountService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 账号表 前端控制器
 * </p>
 *
 * @author 吴彦祖
 * @since 2025年05月14日
 */
@RestController
@RequestMapping("/account")
@Api(tags = "用户模块")
public class AccountController {
    @Autowired
    private AccountService accountService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @ApiOperation("发送注册验证码")
    @GetMapping("/sendLoginCode")
    public Result sendLoginCode(String phone) throws Exception{
        accountService.sendCode(phone);
        return Result.getResult().setMessage("发送成功");
    }
    @ApiOperation("注册")
    @GetMapping ("/add")
    public Result add(AccountDto accountDto) throws Exception{
        accountService.add(accountDto);
        return Result.getResult().setMessage("注册成功");
    }
    @PostMapping("/login")
    @ApiOperation("登录")
    public Result<LoginDto> login(@RequestBody LoginForm form, HttpServletResponse response)throws Exception{
        LoginDto dto=accountService.login(form);
        Map<String, Object> body = BeanUtil.beanToMap(dto);
        //短token
        String accessToken = JwtUtil.createToken(body, 60*60*24,  "askdfjLKASJDFLaksdfdksaslkdfjalksjdf131123iwuerdfjlkasfasdfasdfadf");
        //长token
        String refreshToken = JwtUtil.createToken(body, 60 * 24, "askdfjLKASJDFLaksdfdksaslkdfjalksjdf131123iwuerdfjlkasfasdfasdfadf");

        //短token为键，长token为值，将长token存储到redis中
        stringRedisTemplate.opsForValue().set(accessToken,refreshToken,60*24, TimeUnit.MINUTES);
        //保存一个短token的过期时间
        stringRedisTemplate.opsForValue().set("accessToken:expire"+accessToken,"",10, TimeUnit.MINUTES);
        response.setHeader("Access-Control-Expose-Headers","token");
        response.setHeader("token",accessToken);

        return Result.getResult(LoginDto.class).setData(dto).setMessage("登录成功").setCode(200);
    }

}

